package ds.tree;

public class LevelOrderSpiralTraversal {
	
	private boolean flip = false;
	
	private static class TreeNode{
		int value;
		TreeNode left = null;
		TreeNode right = null;
		
		TreeNode(int val){
			this.value = val;
		}
		
		public String toString(){
			return String.valueOf(value);
		}
	}
	public int height(TreeNode node){
		if(node == null){
			return 0;
		}
		return Math.max(height(node.left) + 1, height(node.right) +1);
	}
	public void iterateLvl(TreeNode node){
		int height = height(node);
		for (int i = 1; i <= height; i++) {
			printLvl(node,i);
			flip = !flip;
		}
	}
	public void printLvl(TreeNode node,int level) {
		if(node == null){
			return;
		}
		if(level == 1){
			System.out.print(node + " ");
		}
		if(flip){
			printLvl(node.left,level-1);
			printLvl(node.right,level-1);
		}	else	{
			printLvl(node.right,level-1);
			printLvl(node.left,level-1);
		}		
	}
	private static TreeNode tree(){
		TreeNode A = new TreeNode(1);
		TreeNode B = new TreeNode(2);
		TreeNode C = new TreeNode(3);
		TreeNode D = new TreeNode(4);
		TreeNode E = new TreeNode(5);
		TreeNode F = new TreeNode(6);
		TreeNode G = new TreeNode(7);	
		TreeNode H = new TreeNode(8);
		TreeNode I = new TreeNode(9);
		
		A.left = B;
		A.right = C;
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		G.left = H;
		G.right = I;
		return A;
	}
	
	public static void main(String[] args) {
		LevelOrderSpiralTraversal spiralTraversal = new LevelOrderSpiralTraversal();
		spiralTraversal.iterateLvl(tree());
	}

}
